import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import app from './modules/app'
import settings from './modules/settings'
import permission from './modules/permission'
import user from './modules/user'
import tagsView from './modules/tagsView'

import { exportSaleProjectExcel } from '@/utils/projectExcel';
import { Message } from 'element-ui'


Vue.use(Vuex)

// https://webpack.js.org/guides/dependency-management/#requirecontext
const modulesFiles = require.context('./modules', true, /\.js$/)

// you do not need `import app from './modules/app'`
// it will auto require all vuex module from modules file
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  // set './app.js' => 'app'
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})

const store = new Vuex.Store({
  state: {
    accept: '.pdf,.docx,.pptx,.ppt,.xlsx,.png,.jpeg,.jpg,.xls,.doc,.txt',
    catchList: '',//固定要缓存组件
    isEventTriggered: false,//是否事件触发跳转
    // --------项目管理导出进度参数 S--------
    showExport: false,
    percentage: 0,
    projectData: [],
    headers: [],
    timerInterval: null,//定时器
    remainingSeconds: 0,//倒数秒数
    // --------项目管理导出进度参数 E--------
  },
  mutations: {
    // 对指定组件进行动态更改缓存（缓存）--组件调用该方法时，判断该组件是否存在于该缓存数组，无则添加
    isKeepAlive(state, component) {
      state.catchList = component;
    },
    // 对指定组件进行动态更改缓存（不缓存）--组件调用该方法时，从缓存数组中删除对应的组件元素
    noKeepAlive(state, component) {
      let index = state.catchList.indexOf(component);
      index > -1 && state.catchList.splice(index, 1);
    },
    // 清空路由
    clearPermissionRoutes(state) {
      state.permission.routes = [];
      state.permission.addRoutes = [];
      state.permission.oldRoutes = [];
      state.permission.allPath = [];
    },
    // 修改事件触发
    isEventTriggeredFunc(state, value) {
      state.isEventTriggered = value;
    },
    // 导出项目列表数据
    async exportProjectFunc(state, value) {
      // console.log(value.total % 100)
      // return;
      state.showExport = true;
      state.percentage = 0.01;
      clearInterval(state.timerInterval);
      let page = Math.ceil(value.total / 100);//计算总页数
      let arr = [];
      let headers = [];
      let percentage = 100 / page;//计算单个进度
      // 计算总秒数   开启倒计时
      state.remainingSeconds = 20 * page;//完成总时长  秒数
      state.timerInterval = setInterval(() => {
        state.remainingSeconds--;//秒数减一
        // 归零   清空定时器
        if (state.remainingSeconds <= 0) {
          clearInterval(state.timerInterval);
          state.remainingSeconds = 0;
        }
      }, 1000);

      console.log(page, "请求次数")
      for (let i = 0; i < page; i++) {
        // 请求要导出的数据
        console.log(`这是第${i + 1}次`)
        let now = new Date().getTime();//请求开始的时间戳
        let obj = await exportSaleProjectExcel(value.field_list, value.formSearch, i + 1, 100)
        if (!obj) {
          Message.warning('项目列表数据导出失败');
          state.showExport = false;
          break;
        }
        // 倒计时未结束，请求已经完成   直接归零秒数，清楚定时器
        if (page == i + 1) {
          clearInterval(state.timerInterval);
          state.remainingSeconds = 0;
        } else {
          let end = new Date().getTime();//请求结束后的时间戳
          let newNum = (end - now) / 1000;
          let pageNew = page - (i + 1);
          console.log(newNum, "上一次接口请求的时长");
          console.log(pageNew, "剩下的次数");
          // 重置倒计时时间   定时器
          clearInterval(state.timerInterval);
          state.remainingSeconds = newNum * pageNew;//完成总时长  秒数
          state.timerInterval = setInterval(() => {
            state.remainingSeconds--;//秒数减一
            // 归零   清空定时器
            if (state.remainingSeconds <= 0) {
              clearInterval(state.timerInterval);
              state.remainingSeconds = 0;
            }
          }, 1000);
        }
        headers = obj.headers;
        arr = [...arr, ...obj.list];
        let numberVal = i + 1 == 1 ? parseFloat((percentage).toString().match(/^\d+(?:\.\d{0,2})?/)) : parseFloat((state.percentage + percentage).toString().match(/^\d+(?:\.\d{0,2})?/));
        console.log(`当前进度${numberVal}%`);
        state.percentage = page == i + 1 ? 100 : Number(numberVal);
        state.projectData = arr;
        state.headers = headers;
      }
    },
  },
  modules,
  getters
})

export default store
